import { createSlice } from "@reduxjs/toolkit";
import {login} from '../../api/login';
import {set_token,get_token} from '../../utils/auth';

const LoginSlice = createSlice({
    name: "login",
    initialState: {
        token:get_token() || '',
    },
    reducers: {
        login_set_token(state,action){
            state.token=action.payload;
            set_token(state.token);
        }
    },
});

const { login_set_token } = LoginSlice.actions;

const loginAsync=(obj)=>{
    return async(dispatch)=>{
        const res=await login(obj);
        if(res.code===0){
            dispatch(login_set_token(res.data.token));
        }
        return res
    } 
}

export {loginAsync}

export default LoginSlice.reducer